<?php
/*
 * 车型信息的获取类
 * @package    auto
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 72b05093cb1ddb06b1d1c07648724ed1338dff2a $
 */

defined('IN_IXDCW') or exit('Access Denied');

/**
 * 车型信息的获取类
 * Class AutoInfo
 */
class AutoInfo {

	const RETURN_JSON       = 'JSON';
	const RETURN_SERIALIZE  = 'SERIALIZE';
	const RETURN_DEFAULT    = 'DEFAULT';
	const PARAM_CHECK_EMPTY = 'EMPTY';
	const PARAM_CHECK_REG   = 'REG';

	private $_db;
	private $_table_brand;
	private $_table_auto;
	private $_table_auto_commercial;
	private $_table_auto_passenger;
	private $_table_auto_rv;
	private $_auto_moduleid;
	private $_table_picture;
	private $_cats;

	public function __construct() {
		global $db;
		$this->_db = & $db;
		// 车型库ID
		$this->_auto_moduleid         = 29;
		$this->_table_brand           = $this->_db->pre . 'auto_category';
		$this->_table_model           = $this->_db->pre . 'auto_model';
		$this->_table_auto            = $this->_db->pre . 'auto_rank_car';
		$this->_table_auto_commercial = $this->_db->pre . 'auto_commercial';
		$this->_table_auto_rv         = $this->_db->pre . 'auto_rv';
		$this->_table_auto_passenger  = $this->_db->pre . 'auto_passenger';
		$this->_table_picture         = $this->_db->pre . 'auto_rank_brand';
		$this->_cats                  = PCache::read('autoCategory-level.php');
	}


	public function getCats($catid = 0) {
		$level    = PCache::read('autoCategory-level.php');
		$leverarr = array();
		if ($catid) {
			$num = explode(',', $level[$catid]['arrchildid']);
			foreach ($num as $v) {
				if ($v != $catid && $level[$v]['parentid'] == $catid) {
					$leverarr[] = $level[$v];
				}
			}
		} else {
			foreach ($level as $v) {
				if (!$v['parentid']) {
					$leverarr[] = $v;
				}
			}
		}
		return $leverarr;
	}

	public function getAllCats() {
		return $this->_cats;
	}



	public function getAuto($modelid) {
		$sql = "select a.*,b.name AS brandname from {$this->_table_auto} AS a,{$this->_table_brand} AS b where aid = {$modelid} AND a.bid=b.id";
		return $this->_db->getOne($sql);
	}


	public function getBrandsByEnginType($enginType) {
		global $CFG, $str, $arbid;
		$enginTypes = PCache::read('autoCategory-engine.php');

		$typeid = $enginTypes[$enginType]['arrchildid'];
		$sql    = "select distinct (arbid) from {$this->_table_model} where 1 and enginetype in (" . $typeid . ")";
		$str    = $this->_db->getAll($sql);
		$arbid  = '';
		foreach ($str as $v) {
			$arbid .= $v['arbid'] . ',';
		}
		$arbid  = substr($arbid, 0, -1);
		$sql    = "select {$this->_table_brand}.arid, name, letter, brand_thumb from {$this->_table_brand},{$this->_table_picture } where  {$this->_table_brand}.arid = {$this->_table_picture }.arid  and {$this->_table_brand}.arid in(" . $arbid . ")";
		$brands = $this->_db->getAll($sql, $CFG['db_expires'] ? 'CACHE' : '', $CFG['db_expires']);
		usort($brands, 'xd_catsort');
		$result = array();
		foreach ($brands as $brand) {
			$result[$brand['arid']] = array(
				'brandID'        => $brand['arid'],
				'brandName'      => $brand['letter'] . '-' . $brand['name'],
				'brandletter'    => $brand['letter'],
				'brandShortName' => $brand['name'],
				'brandThumb'     => $brand['brand_thumb']
			);
		}
		return $result;
	}

	public function getBrands($catid) {
		global $CFG, $str, $arbid;
		$catid = $this->_cats[$catid]['arrchildid'];
		$sql   = "select distinct (arbid) from {$this->_table_model} where 1 and acid in (" . $catid . ")";
		$str   = $this->_db->getAll($sql);
		$arbid = '';
		foreach ($str as $v) {
			$arbid .= $v['arbid'] . ',';
		}
		$arbid  = substr($arbid, 0, -1);
		$sql    = "select {$this->_table_brand}.arid, name, letter, brand_thumb from {$this->_table_brand},{$this->_table_picture } where  {$this->_table_brand}.arid = {$this->_table_picture }.arid  and {$this->_table_brand}.arid in(" . $arbid . ")";
		$brands = $this->_db->getAll($sql, $CFG['db_expires'] ? 'CACHE' : '', $CFG['db_expires']);
		usort($brands, 'xd_catsort');
		$result = array();
		foreach ($brands as $brand) {
			$result[$brand['arid']] = array(
				'brandID'        => $brand['arid'],
				'brandName'      => $brand['letter'] . '-' . $brand['name'],
				'brandletter'    => $brand['letter'],
				'brandShortName' => $brand['name'],
				'brandThumb'     => $brand['brand_thumb']
			);
		}
		return $result;
	}

	public function fullJS($result) {
		if ($result) {
			return array(
				'Error'  => 0,
				'Result' => $result
			);
		} else {
			return array(
				'Error' => 1,
				'Msg'   => 'Result is Null'
			);
		}
	}

	public function getModels($brandid) {
		$sql        = "select arrchildid from ($this->_table_brand) where arid=" . $brandid;
		$arrchildid = $this->_db->getAll($sql);
		$arrchildid = $arrchildid[0]['arrchildid'];
		$sql        = "select arid, name,parentid,child from {$this->_table_brand} where arid in ($arrchildid)";
		$models     = $this->_db->getAll($sql);
		array_shift($models);
		$result = array();
		foreach ($models as $model) {
			if ($model['parentid'] == $brandid && $model['child']) {
				$result[$model['arid']] = array(
					'modelID'   => $model['arid'],
					'modelName' => $model['name'],
					'typeId'    => $model['parentid'],
					'child'     => $model['child'],
				);
			}
		}
		if ($result) {
			return $result;
		}
		foreach ($models as $model) {
			$result[$model['arid']] = array(
				'modelID'   => $model['arid'],
				'modelName' => $model['name'],
				'typeId'    => $model['parentid'],
				'child'     => $model['child'],
			);
		}
		return $result;
	}

	public function fullVarsByModelid($modelid) {
		// aid 车型ID
		// cid 分类id
		// bid 品牌ID
		$auto = $this->getModel($modelid);
		if (!$auto) {
			$arbid = $this->getBrand($modelid);
			$arbid = $this->getBrand($arbid['parentid']);
			$arbid = $arbid['parentid'];
			$auto  = $this->getModelbid($arbid);
		}
		$result            = array();
		$result['modelid'] = $auto['armid'];
		$result['bid']     = $auto['arbid'];

		return $result;
	}

	public function fullCtp($ctp) {
		$ctps        = explode(',', $this->_cats[$ctp]['arrparentid'] . ',' . $ctp);
		$CAR         = array();
		$CAR['ctpa'] = isset($ctps[1]) ? intval($ctps[1]) : 0;
		$num         = count($ctps) - 1;
		if ($num != 1) {
			$CAR['ctpb'] = isset($ctps[$num]) ? intval($ctps[$num]) : 0;
		}

		return $CAR;
	}

	/**
	 * 获取所有车款
	 */
	function getStyles($modelid) {
		//获取相关车款列表
		$sql    = "SELECT amid,name,year FROM {$this->_table_model} WHERE arcid={$modelid}";
		$result = $this->_db->getAll($sql);
		$cars   = array();
		foreach ($result as $r) {
			$cars[$r['amid']] = array(
				'carID'   => $r['amid'],
				'carName' => $r['name'],
				'year'    => $r['year'],
			);
		}
		return $cars;
	}

	/**
	 * 获取车款信息
	 * @param $modelid
	 * @param $styleid
	 * @return mixed
	 */
	public function getStyle($modelid, $styleid) {
		$model = $this->getModel($modelid);
		$table = $this->_getTable($model['typeid']);
		return $this->_db->getOne("select * from {$table} where id=$styleid");
	}


	public function getBrand($brandid) {
		$sql = "select * from {$this->_table_brand} where arid = {$brandid}";
		return $this->_db->getOne($sql);
	}

	/**
	 * 根据车系级别获取品牌信息
	 * @param $ctp
	 * @return mixed
	 */
	public function getcatBrand($ctp) {
		if ($this->_cats[$ctp]['arrchildid']) $ctp = $this->_cats[$ctp]['arrchildid'];
		$sql = "select distinct(arbid) from {$this->_table_model} where acid in ($ctp)";
		return $this->_db->getAll($sql);
	}

	/**
	 * 获取$modelid品牌下的车系id
	 * @param $modelid
	 * @return mixed
	 */
	public function getModelid($modelid) {
		$sql = "select arrchildid from {$this->_table_brand} where arid=" . $modelid;
		return $this->_db->getOne($sql);
	}

	/**
	 * 根据车系id获取车型
	 * @param $modelid
	 * @return mixed
	 */
	public function getModel($modelid) {
		$sql = "select * from {$this->_table_model} where arcid=" . $modelid;
		return $this->_db->getOne($sql);
	}

	/**
	 * 根据品牌id获取车型
	 * @param $brandid
	 * @return mixed
	 */
	public function getModelbid($brandid) {
		$sql = "select * from {$this->_table_model} where arbid=" . $brandid;
		return $this->_db->getOne($sql);
	}

	/**
	 * 根据品牌id获取级别
	 * @param $cid
	 * @return mixed
	 */
	public function getCid($cid) {
		$level    = PCache::read('autoCategory-level.php');
		$leverarr = $level[$cid]['arrchildid'];
		$sql      = "select distinct (arbid) from {$this->_table_model} where acid in(" . $leverarr . ")";
		$arcid    = $this->_db->getAll($sql);
		$result   = array();
		foreach ($arcid as $v) {
			$result[$v['arbid']] = array(
				'brandID' => $v['arbid'],
			);
		}
		return $result;
	}

	/**
	 * 获取子类车型的品牌链接SQL
	 * @param $catid
	 * @param $field
	 * @return string
	 */
	private function _catsSql($catid, $field) {
		$cats = PCache::read('autoCategory-level.php');
		if (isset($cats[$catid]['arrchildid'])) {
			return ' and ' . $field . ' in (' . $cats[$catid]['arrchildid'] . ')';
		} else {
			return ' and ' . $field . '=' . $catid;
		}
	}

	/**
	 * 根据品牌获取车型级别
	 * @param $arbid 品牌ID
	 * @param $arcid 车系ID
	 * @param $amid  车款ID
	 * @return array
	 */
	public static function  byAcid($arbid, $arcid, $amid) {
		global $db;
		if ($arbid[0]) {
			foreach ($arbid as $v) {
				if (!preg_match("/^\d*$/", $v)) {
					$arbid = '';
				}
			}
			sort($arbid);
			$car['arbid'] = implode(',', $arbid);
			$sql          = 'select distinct(acid) from xd_auto_model where arbid in (' . $car['arbid'] . ')';
			$acid         = $db->getAll($sql);
			$level        = PCache::read('autoCategory-level.php');
			foreach ($acid as $v) {
				if ($v['acid'] != 0) {
					$acid[] = $v['acid'];
					$acid[] = $level[$v['acid']]['parentid'];
				}
			}
			$acid = array_flip(array_flip($acid));
			sort($acid);
			$car['acid'] = implode(',', $acid);
		} else {
			$car['arbid'] = '';
			$car['arcid'] = '';
			$car['amid']  = '';
		}
		if ($arcid && $arbid) {
			foreach ($arcid as $v) {
				if (!preg_match("/^\d*$/", $v)) {
					$arcid = '';
				}
			}
			sort($arcid);
			$car['arcid'] = implode(',', $arcid);
		} else {
			$car['arcid'] = '';
			$car['amid']  = '';
		}
		if ($arcid && $arbid && $amid) {
			foreach ($amid as $v) {
				if (!preg_match("/^\d*$/", $v)) {
					$amid = '';
				}
			}
			sort($amid);
			$car['amid'] = implode(',', $amid);
		} else {
			$car['amid'] = '';
		}
		return $car;
	}

	/**
	 * 获取表名称
	 * @param $type
	 * @return string
	 */
	private function _getTable($type) {
		if ($type == 1)
			return $this->_table_auto_passenger;
		if ($type == 2)
			return $this->_table_auto_commercial;
		if ($type == 3)
			return $this->_table_auto_rv;
	}

	/**
	 * 格式化结果
	 * @param        $return
	 * @param string $type
	 * @return string
	 */
	public function getResult($return, $type = self::RETURN_JSON) {
		switch ($type) {
			case self::RETURN_JSON:
				return json_encode($return);
				break;
			case self::RETURN_SERIALIZE:
				return serialize($return);
				break;
			default :
				return $return;
		}
	}

}